"""
热成像温度分析器
主界面控制器，协调各个组件完成温度分析功能
"""

import sys
import os
import cv2
import numpy as np
from PyQt5.QtWidgets import (QApplication, QMainWindow, QVBoxLayout, QHBoxLayout, 
                             QWidget, QPushButton, QLabel, QFileDialog, QSpinBox, 
                             QDoubleSpinBox, QGroupBox, QGridLayout, QTextEdit,
                             QScrollArea, QSplitter, QFrame, QMessageBox, QLineEdit,
                             QTabWidget, QCheckBox, QSlider, QListWidget, QListWidgetItem,
                             QComboBox)
from PyQt5.QtCore import Qt, pyqtSignal
from PyQt5.QtGui import QPixmap, QImage, QPainter, QPen, QColor, QFont

from .image_widget import ImageLabel
# 导入服务层
from .thermal_analyzer_service import ThermalAnalysisService
from ..core.hybrid_temperature_processor import get_hybrid_processor


class ThermalAnalyzer(QMainWindow):
    def __init__(self):
        super().__init__()
        # 使用服务层进行业务逻辑处理
        self.thermal_service = ThermalAnalysisService()
        self.hybrid_processor = get_hybrid_processor()
        
        # TSDK相关状态
        self.current_processing_mode = 'auto'  # auto, hsv, tsdk, hybrid
        self.tsdk_capabilities = None
        
        self.initUI()
        
        # 初始化标定点列表
        self.refresh_calibration_list()
        
        # 初始化标定点显示（如果有已加载的标定点）
        self.update_calibration_display()
        
        # 初始化TSDK能力检查
        self.check_tsdk_capabilities()
        
    def initUI(self):
        self.setWindowTitle('红外热成像温度分析系统')
        self.setGeometry(100, 100, 1200, 800)
        
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        # 主布局
        main_layout = QHBoxLayout(central_widget)
        
        # 创建分割器
        splitter = QSplitter(Qt.Horizontal)
        main_layout.addWidget(splitter)
        
        # 左侧面板 - 图像显示
        left_panel = self.create_image_panel()
        splitter.addWidget(left_panel)
        
        # 右侧面板 - 控制和结果
        right_panel = self.create_control_panel()
        splitter.addWidget(right_panel)
        
        # 设置分割比例
        splitter.setSizes([600, 400])
        
    def create_image_panel(self):
        panel = QWidget()
        layout = QVBoxLayout(panel)
        
        # 图像显示区域
        self.image_label = ImageLabel()
        self.image_label.setText("点击'加载图片'选择热成像图片")
        self.image_label.clicked.connect(self.on_image_clicked_tsdk)  # 使用TSDK增强版
        self.image_label.area_selected.connect(self.on_area_selected)
        self.image_label.area_completed.connect(self.on_area_completed_auto_analyze)  # 自动分析
        
        scroll_area = QScrollArea()
        scroll_area.setWidget(self.image_label)
        scroll_area.setWidgetResizable(True)
        
        layout.addWidget(scroll_area)
        
        # 图像控制按钮
        button_layout = QHBoxLayout()
        
        load_btn = QPushButton('加载图片')
        load_btn.clicked.connect(self.load_image)
        button_layout.addWidget(load_btn)
        
        layout.addLayout(button_layout)
        
        # 区域分析按钮
        area_layout = QHBoxLayout()
        
        
        clear_areas_btn = QPushButton('清空区域')
        clear_areas_btn.clicked.connect(self.clear_analysis_areas)
        area_layout.addWidget(clear_areas_btn)
        
        
        layout.addLayout(area_layout)
        
        return panel
        
    def create_control_panel(self):
        panel = QWidget()
        layout = QVBoxLayout(panel)
        
        # 标定控制
        calibration_group = QGroupBox("温度标定")
        cal_layout = QGridLayout(calibration_group)
        
        cal_layout.addWidget(QLabel("标定模式:"), 0, 0)
        self.cal_mode_btn = QPushButton("开始标定")
        self.cal_mode_btn.clicked.connect(self.toggle_calibration_mode)
        cal_layout.addWidget(self.cal_mode_btn, 0, 1)
        
        cal_layout.addWidget(QLabel("参考温度:"), 1, 0)
        self.ref_temp_spin = QDoubleSpinBox()
        self.ref_temp_spin.setRange(-50, 200)
        self.ref_temp_spin.setValue(25.0)
        self.ref_temp_spin.setSuffix("°C")
        cal_layout.addWidget(self.ref_temp_spin, 1, 1)
        
        
        layout.addWidget(calibration_group)
        
        # TSDK处理模式控制
        tsdk_group = QGroupBox("TSDK处理模式")
        tsdk_layout = QGridLayout(tsdk_group)
        
        tsdk_layout.addWidget(QLabel("处理模式:"), 0, 0)
        
        # 处理模式选择
        self.processing_mode_combo = QComboBox()
        self.processing_mode_combo.addItems(['自动选择', 'HSV映射', 'TSDK精确', '混合模式'])
        self.processing_mode_combo.currentTextChanged.connect(self.on_processing_mode_changed)
        tsdk_layout.addWidget(self.processing_mode_combo, 0, 1)
        
        # TSDK状态指示
        self.tsdk_status_label = QLabel("TSDK状态: 检查中...")
        tsdk_layout.addWidget(self.tsdk_status_label, 1, 0, 1, 2)
        
        # 能力检查按钮
        check_capabilities_btn = QPushButton("检查TSDK能力")
        check_capabilities_btn.clicked.connect(self.check_tsdk_capabilities)
        tsdk_layout.addWidget(check_capabilities_btn, 2, 0, 1, 2)
        
        
        layout.addWidget(tsdk_group)
        
        # 结果显示
        result_group = QGroupBox("分析结果")
        result_layout = QVBoxLayout(result_group)
        
        self.result_text = QTextEdit()
        self.result_text.setMaximumHeight(150)
        self.result_text.setReadOnly(True)
        result_layout.addWidget(self.result_text)
        
        layout.addWidget(result_group)
        
        # 标定点管理
        calibration_mgr_group = QGroupBox("标定点管理")
        cal_mgr_layout = QVBoxLayout(calibration_mgr_group)
        
        # 标定点列表
        self.calibration_list = QListWidget()
        self.calibration_list.setMaximumHeight(200)
        cal_mgr_layout.addWidget(self.calibration_list)
        
        # 标定点操作按钮
        cal_ops_layout = QHBoxLayout()
        
        self.toggle_cal_btn = QPushButton("隐藏标定点")
        self.toggle_cal_btn.clicked.connect(self.toggle_calibration_display)
        self.show_calibration = True  # 默认显示标定点
        cal_ops_layout.addWidget(self.toggle_cal_btn)
        
        delete_cal_btn = QPushButton("删除选中")
        delete_cal_btn.clicked.connect(self.delete_selected_calibration)
        cal_ops_layout.addWidget(delete_cal_btn)
        
        delete_all_cal_btn = QPushButton("删除全部")
        delete_all_cal_btn.clicked.connect(self.delete_all_calibration)
        delete_all_cal_btn.setStyleSheet("background-color: #ff4444; color: white;")
        cal_ops_layout.addWidget(delete_all_cal_btn)
        
        cal_mgr_layout.addLayout(cal_ops_layout)
        
        # 标定点统计信息
        self.cal_info_label = QLabel("标定点数量: 0")
        cal_mgr_layout.addWidget(self.cal_info_label)
        
        layout.addWidget(calibration_mgr_group)
        
        
        return panel
        
    def load_image(self):
        file_path, _ = QFileDialog.getOpenFileName(
            self, "选择热成像图片", "", "图片文件 (*.png *.jpg *.jpeg *.bmp *.tiff);;R-JPEG文件 (*.r.jpg *.rjpeg);;所有文件 (*.*)"
        )
        
        if file_path:
            try:
                # 使用混合处理器处理图像
                force_mode = self.get_current_processing_mode()
                result = self.hybrid_processor.process_image(file_path, force_mode=force_mode)
                
                # 同时使用原有服务加载图像用于显示
                if self.thermal_service.load_image_from_file(file_path):
                    # 获取加载的图像并显示
                    image = self.thermal_service.current_image
                    if image is not None:
                        # 转换为Qt图像并显示
                        height, width, channel = image.shape
                        bytes_per_line = 3 * width
                        q_image = QImage(image.data, width, height, bytes_per_line, QImage.Format_RGB888).rgbSwapped()
                        pixmap = QPixmap.fromImage(q_image)
                        
                        self.image_label.set_image(pixmap)
                        
                        # 显示处理结果信息
                        processing_method = result.get('processing_method', 'unknown')
                        accuracy_level = result.get('accuracy_level', 'unknown')
                        
                        info_text = f"图片加载成功: {os.path.basename(file_path)}\n"
                        info_text += f"处理方式: {processing_method}\n"
                        info_text += f"精度级别: {accuracy_level}\n"
                        info_text += f"温度范围: {result['min_temp']:.2f}°C - {result['max_temp']:.2f}°C\n"
                        info_text += f"平均温度: {result['mean_temp']:.2f}°C"
                        
                        self.result_text.append(info_text)
                        
                        # 如果是混合模式，显示对比信息
                        if processing_method == 'hybrid' and 'method_comparison' in result:
                            comparison = result['method_comparison']
                            comp_text = f"\n方法对比:\n"
                            comp_text += f"  平均差异: {comparison['mean_difference']:.2f}°C\n"
                            comp_text += f"  最大差异: {comparison['max_difference']:.2f}°C\n"
                            comp_text += f"  相关系数: {comparison['correlation']:.3f}"
                            self.result_text.append(comp_text)
                else:
                    QMessageBox.warning(self, "错误", "图像显示失败")
                    
            except Exception as e:
                QMessageBox.warning(self, "错误", f"加载图片失败: {str(e)}")
                self.result_text.append(f"错误: {str(e)}")
                
    def toggle_calibration_mode(self):
        current_mode = self.thermal_service.is_calibration_mode()
        new_mode = not current_mode
        self.thermal_service.set_calibration_mode(new_mode)
        
        if new_mode:
            # 开启标定模式
            self.cal_mode_btn.setText("结束标定")
            # 关闭区域选择模式，避免冲突
            self.image_label.set_area_selection_mode(False)
            self.result_text.append("标定模式已开启，点击图像添加标定点")
        else:
            # 关闭标定模式
            self.cal_mode_btn.setText("开始标定")
            self.result_text.append("标定模式已关闭")
            
    def on_image_clicked(self, x, y):
        if not self.thermal_service.has_image():
            return
            
        if self.thermal_service.is_calibration_mode():
            # 添加标定点
            ref_temp = self.ref_temp_spin.value()
            success = self.thermal_service.add_calibration_point(x, y, ref_temp)
            
            if success:
                # 获取像素信息
                pixel_info = self.thermal_service.get_pixel_temperature(x, y)
                if pixel_info:
                    points_count = len(self.thermal_service.get_calibration_points())
                    self.result_text.append(f"添加标定点 #{points_count}:")
                    self.result_text.append(f"  位置: {pixel_info['position']}")
                    self.result_text.append(f"  温度: {ref_temp:.1f}°C")
                    self.result_text.append(f"  HSV: {pixel_info['hsv']}")
                    self.result_text.append(f"  RGB: {pixel_info['rgb']}")
                    self.result_text.append("---")
                    
                    # 更新图像显示标定点
                    self.update_calibration_display()
        else:
            # 显示点击位置的温度和颜色信息
            pixel_info = self.thermal_service.get_pixel_temperature(x, y)
            if pixel_info:
                self.result_text.append(f"位置{pixel_info['position']}:")
                self.result_text.append(f"  估计温度: {pixel_info['temperature']:.1f}°C")
                self.result_text.append(f"  HSV: {pixel_info['hsv']}")
                self.result_text.append(f"  RGB: {pixel_info['rgb']}")
            
    def update_calibration_display(self):
        """更新标定点的可视化显示"""
        calibration_points = self.thermal_service.temp_mapper.get_calibration_info()
        
        # 只有在显示状态时才绘制标定点
        if hasattr(self, 'show_calibration') and self.show_calibration:
            if calibration_points:
                self.image_label.draw_calibration_points(calibration_points)
        else:
            # 隐藏状态时清除标定点显示
            self.image_label.draw_calibration_points([])
            
        # 同时刷新标定点列表
        self.refresh_calibration_list()
            
    def save_calibration_data(self):
        """保存标定点数据"""
        file_path = self.thermal_service.save_calibration_data()
        if file_path:
            self.result_text.append(f"标定数据已保存: {file_path}")
        else:
            self.result_text.append("保存标定数据失败")
    
    def clear_calibration(self):
        self.thermal_service.clear_calibration_points()
        self.result_text.append("标定点已清空")
        
        # 重新显示原始图像（移除标定点标记）
        if self.thermal_service.has_image():
            image = self.thermal_service.current_image
            height, width, channel = image.shape
            bytes_per_line = 3 * width
            q_image = QImage(image.data, width, height, bytes_per_line, QImage.Format_RGB888).rgbSwapped()
            pixmap = QPixmap.fromImage(q_image)
            self.image_label.set_image(pixmap)
            
        # 刷新标定点列表
        self.refresh_calibration_list()
    
    def refresh_calibration_list(self):
        """刷新标定点列表显示"""
        self.calibration_list.clear()
        calibration_points = self.thermal_service.get_calibration_points()
        
        for point in calibration_points:
            pos = point.position
            temp = point.temperature
            hsv = point.hsv_color
            
            # 创建列表项文本
            item_text = f"标定点 {point.index+1}: ({pos[0]}, {pos[1]}) - {temp:.1f}°C"
            detail_text = f"HSV: ({hsv[0]:.0f}, {hsv[1]:.0f}, {hsv[2]:.0f})"
            full_text = f"{item_text}\n{detail_text}"
            
            # 添加到列表
            item = QListWidgetItem(full_text)
            item.setData(Qt.UserRole, point.index)  # 存储标定点索引
            self.calibration_list.addItem(item)
        
        # 更新统计信息
        count = len(calibration_points)
        self.cal_info_label.setText(f"标定点数量: {count}")
        
        if count > 0:
            self.result_text.append(f"已刷新标定点列表，共{count}个标定点")
    
    def toggle_calibration_display(self):
        """切换标定点显示/隐藏状态"""
        self.show_calibration = not self.show_calibration
        
        if self.show_calibration:
            # 显示标定点
            self.toggle_cal_btn.setText("隐藏标定点")
            # 重新绘制标定点
            calibration_points = self.thermal_service.get_calibration_points()
            # 转换CalibrationPoint对象为字典格式
            points_dict = []
            for point in calibration_points:
                points_dict.append({
                    'position': point.position,
                    'temperature': point.temperature
                })
            self.image_label.draw_calibration_points(points_dict)
            self.result_text.append("已显示标定点")
        else:
            # 隐藏标定点
            self.toggle_cal_btn.setText("显示标定点")
            # 清除标定点显示
            self.image_label.draw_calibration_points([])
            self.result_text.append("已隐藏标定点")
    
    def delete_selected_calibration(self):
        """删除选中的标定点"""
        current_item = self.calibration_list.currentItem()
        if current_item is None:
            QMessageBox.information(self, "提示", "请先选择要删除的标定点")
            return
            
        # 获取标定点索引
        point_index = current_item.data(Qt.UserRole)
        calibration_points = self.thermal_service.get_calibration_points()
        
        if 0 <= point_index < len(calibration_points):
            # 确认删除
            point = calibration_points[point_index]
            pos = point.position
            temp = point.temperature
            
            reply = QMessageBox.question(
                self, "确认删除",
                f"确定要删除标定点 {point_index+1}?\n"
                f"位置: ({pos[0]}, {pos[1]})\n"
                f"温度: {temp:.1f}°C",
                QMessageBox.Yes | QMessageBox.No,
                QMessageBox.No
            )
            
            if reply == QMessageBox.Yes:
                # 删除指定标定点
                success = self.thermal_service.delete_calibration_point(point_index)
                if success:
                    self.result_text.append(f"已删除标定点 {point_index+1}: ({pos[0]}, {pos[1]}) - {temp:.1f}°C")
                    self.refresh_calibration_list()
                    self.update_calibration_display()
    
    def delete_all_calibration(self):
        """删除所有标定点"""
        calibration_points = self.thermal_service.get_calibration_points()
        
        if not calibration_points:
            QMessageBox.information(self, "提示", "当前没有标定点需要删除")
            return
            
        # 确认删除所有标定点
        reply = QMessageBox.question(
            self, "确认删除",
            f"确定要删除所有 {len(calibration_points)} 个标定点吗？\n\n"
            "此操作不可撤销！",
            QMessageBox.Yes | QMessageBox.No,
            QMessageBox.No
        )
        
        if reply == QMessageBox.Yes:
            # 删除所有标定点
            self.thermal_service.clear_calibration_points()
            self.result_text.append(f"已删除所有 {len(calibration_points)} 个标定点")
            
            # 刷新界面显示
            self.refresh_calibration_list()
            self.update_calibration_display()
            
            # 重新显示原始图像（移除标定点标记）
            if self.thermal_service.has_image():
                image = self.thermal_service.current_image
                height, width, channel = image.shape
                bytes_per_line = 3 * width
                q_image = QImage(image.data, width, height, bytes_per_line, QImage.Format_RGB888).rgbSwapped()
                pixmap = QPixmap.fromImage(q_image)
                self.image_label.set_image(pixmap)
    
    
    def on_area_selected(self, x1, y1, x2, y2):
        """处理区域选择事件"""
        width = x2 - x1
        height = y2 - y1
        area_num = len(self.image_label.selected_areas)
        
        self.result_text.append(f"选择了区域{area_num}:")
        self.result_text.append(f"  范围: ({x1}, {y1}) 到 ({x2}, {y2})")
        self.result_text.append(f"  大小: {width} × {height} 像素")
        self.result_text.append("---")
    
    def clear_analysis_areas(self):
        """清空分析区域"""
        self.image_label.clear_selected_areas()
        self.result_text.append("已清空所有分析区域")
    
        
    def on_area_completed_auto_analyze(self, x1, y1, x2, y2):
        """区域选择完成后自动分析温度"""
        if not self.hybrid_processor.current_data:
            return
        
        try:
            # 使用混合处理器分析区域
            stats = self.hybrid_processor.get_region_temperature_stats(x1, y1, x2, y2)
            
            # 获取当前区域编号
            area_num = len(self.image_label.selected_areas)
            
            # 显示简化的分析结果
            self.result_text.append(f"区域 {area_num} 分析完成: 平均温度 {stats['mean_temp']:.1f}°C")
            self.result_text.append("---")
            
            # 确保滚动到底部并强制刷新
            self.result_text.verticalScrollBar().setValue(self.result_text.verticalScrollBar().maximum())
            self.result_text.repaint()
            
            # 更新图像显示统计信息
            min_pos = stats['min_position']
            max_pos = stats['max_position']
            
            area_statistics = [{
                'min_temp': stats['min_temp'],
                'max_temp': stats['max_temp'],
                'avg_temp': stats['mean_temp'],
                'temp_diff': stats['max_temp'] - stats['min_temp'],
                'pixel_count': (x2-x1) * (y2-y1)
            }]
            
            extreme_points = [{
                'min_temp': stats['min_temp'],
                'max_temp': stats['max_temp'],
                'min_point': (min_pos['x'], min_pos['y']),
                'max_point': (max_pos['x'], max_pos['y'])
            }]
            
            # 如果是第一个区域，直接设置；否则追加
            if len(self.image_label.area_statistics) < area_num:
                self.image_label.area_statistics.extend(area_statistics)
                self.image_label.extreme_points.extend(extreme_points)
            else:
                # 更新现有区域的统计信息
                self.image_label.area_statistics[area_num-1] = area_statistics[0]
                self.image_label.extreme_points[area_num-1] = extreme_points[0]
            
            self.image_label.update_area_display()
            
        except Exception as e:
            self.result_text.append(f"自动区域分析失败: {str(e)}")
            self.result_text.verticalScrollBar().setValue(self.result_text.verticalScrollBar().maximum())
            self.result_text.repaint()
    
    def analyze_selected_areas(self):
        """分析选中的区域"""
        if not self.thermal_service.has_image():
            QMessageBox.warning(self, "警告", "请先加载图片")
            return
            
        if not self.image_label.selected_areas:
            QMessageBox.warning(self, "警告", "请先选择分析区域")
            return
        
        self.result_text.append("开始分析选中区域的温度分布...")
        
        # 构建区域数据
        regions = []
        for x1, y1, x2, y2 in self.image_label.selected_areas:
            regions.append({'x1': x1, 'y1': y1, 'x2': x2, 'y2': y2})
        
        # 调用服务层进行区域分析
        results = self.thermal_service.analyze_regions_temperature(regions)
        
        # 显示结果
        for result in results:
            analysis = result.analysis_result
            self.result_text.append(f"区域{result.region_id} 温度分析结果:")
            self.result_text.append(f"  最低温度: {analysis.min_temp:.1f}°C (位置: {analysis.min_pos})")
            self.result_text.append(f"  最高温度: {analysis.max_temp:.1f}°C (位置: {analysis.max_pos})")
            self.result_text.append(f"  平均温度: {analysis.avg_temp:.1f}°C")
            self.result_text.append(f"  温差: {analysis.temp_diff:.1f}°C")
            self.result_text.append(f"  像素数量: {analysis.pixel_count}")
            self.result_text.append("---")
        
        # 更新图像显示
        if results:
            area_statistics = []
            extreme_points = []
            
            for result in results:
                analysis = result.analysis_result
                stats = {
                    'min_temp': analysis.min_temp,
                    'max_temp': analysis.max_temp,
                    'avg_temp': analysis.avg_temp,
                    'temp_diff': analysis.temp_diff,
                    'pixel_count': analysis.pixel_count
                }
                area_statistics.append(stats)
                
                extreme_point = {
                    'min_temp': analysis.min_temp,
                    'max_temp': analysis.max_temp,
                    'min_point': analysis.min_pos,
                    'max_point': analysis.max_pos
                }
                extreme_points.append(extreme_point)
            
            self.image_label.update_area_statistics(area_statistics, extreme_points)
    
    def check_tsdk_capabilities(self):
        """检查TSDK处理能力"""
        try:
            capabilities = self.hybrid_processor.get_processing_capabilities()
            self.tsdk_capabilities = capabilities
            
            # 更新状态显示
            if capabilities['tsdk_available']:
                status_text = "TSDK状态: 可用 ✓"
                self.tsdk_status_label.setStyleSheet("color: green; font-weight: bold;")
            else:
                status_text = "TSDK状态: 不可用 (使用模拟模式)"
                self.tsdk_status_label.setStyleSheet("color: orange; font-weight: bold;")
            
            self.tsdk_status_label.setText(status_text)
            
            # 在结果区域显示详细信息
            self.result_text.append("TSDK能力检查完成:")
            self.result_text.append(f"  TSDK可用: {'是' if capabilities['tsdk_available'] else '否'}")
            self.result_text.append(f"  HSV可用: {'是' if capabilities['hsv_available'] else '否'}")
            self.result_text.append(f"  混合模式: {'是' if capabilities['hybrid_available'] else '否'}")
            self.result_text.append(f"  标定支持: {'是' if capabilities['calibration_support'] else '否'}")
            self.result_text.append(f"  实时处理: {'是' if capabilities['real_time_processing'] else '否'}")
            
        except Exception as e:
            self.tsdk_status_label.setText("TSDK状态: 检查失败")
            self.tsdk_status_label.setStyleSheet("color: red; font-weight: bold;")
            self.result_text.append(f"TSDK能力检查失败: {str(e)}")
    
    def on_processing_mode_changed(self, text):
        """处理模式变更事件"""
        mode_map = {
            '自动选择': 'auto',
            'HSV映射': 'hsv', 
            'TSDK精确': 'tsdk',
            '混合模式': 'hybrid'
        }
        
        self.current_processing_mode = mode_map.get(text, 'auto')
        
        # 检查是否可以使用选择的模式
        if self.tsdk_capabilities:
            if self.current_processing_mode == 'tsdk' and not self.tsdk_capabilities['tsdk_available']:
                QMessageBox.warning(self, "警告", 
                                  "TSDK不可用，将自动切换到模拟模式。\n"
                                  "如需使用真实TSDK功能，请确保已正确安装DJI Thermal SDK。")
            
            elif self.current_processing_mode == 'hybrid' and not self.tsdk_capabilities['hybrid_available']:
                QMessageBox.warning(self, "警告", 
                                  "混合模式需要TSDK支持，将回退到HSV模式。")
                self.current_processing_mode = 'hsv'
                self.processing_mode_combo.setCurrentText('HSV映射')
        
        self.result_text.append(f"处理模式已切换到: {text}")
    
    def get_current_processing_mode(self):
        """获取当前处理模式（用于图像加载时的强制模式）"""
        if self.current_processing_mode == 'auto':
            return None  # 自动选择
        return self.current_processing_mode
    
    def on_image_clicked_tsdk(self, x, y):
        """处理图像点击事件（TSDK增强版）"""
        if not self.thermal_service.has_image():
            return
            
        if self.thermal_service.is_calibration_mode():
            # 添加标定点
            ref_temp = self.ref_temp_spin.value()
            
            # 使用热成像服务添加标定点（确保数据同步）
            success = self.thermal_service.add_calibration_point(x, y, ref_temp)
            
            if success:
                # 获取标定点信息
                calibration_points = self.thermal_service.get_calibration_points()
                points_count = len(calibration_points)
                
                self.result_text.append(f"添加标定点 #{points_count}:")
                self.result_text.append(f"  位置: ({x}, {y})")
                self.result_text.append(f"  参考温度: {ref_temp:.1f}°C")
                self.result_text.append("---")
                
                # 更新显示
                self.update_calibration_display()
        else:
            # 非标定模式：启用区域选择模式
            self.image_label.set_area_selection_mode(True)
            self.result_text.append("区域选择模式已开启 - 拖拽鼠标选择分析区域")
    
    
